package com.anxin.registerManagement.service;

import cn.hutool.core.util.ObjectUtil;
import com.anxin.registerManagement.bean.dto.PermissionGroupDto;
import com.anxin.registerManagement.bean.jo.PermissionGroupSearchJo;
import com.anxin.registerManagement.bean.persist.Permission;
import com.anxin.registerManagement.bean.persist.PermissionGroup;
import com.anxin.registerManagement.bean.persist.relation.PermissionGroupPermissionRelation;
import com.anxin.registerManagement.mapper.PermissionGroupMapper;
import com.anxin.registerManagement.mapper.PermissionMapper;
import com.anxin.registerManagement.mapper.relation.PermissionGroupPermissionRelationMapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author 叶前呈
 * @date 2022/1/31 13:43
 */
@Service
public class PermissionGroupService {

    private static Logger logger = LoggerFactory.getLogger(PermissionGroupService.class);

    @Autowired
    PermissionGroupMapper permissionGroupMapper;

    @Autowired
    PermissionMapper permissionMapper;

    @Autowired
    PermissionGroupPermissionRelationMapper permissionGroupPermissionRelationMapper;

    /**
     * 查询权限组
     */
    public PageInfo<PermissionGroupDto> getPermissionGroupList(PermissionGroupSearchJo permissionGroupSearchJo) {
        if (!ObjectUtil.isEmpty(permissionGroupSearchJo.getPageNum()) && !ObjectUtil.isEmpty(permissionGroupSearchJo.getPageSize())) {
            PageHelper.startPage(permissionGroupSearchJo.getPageNum(), permissionGroupSearchJo.getPageSize());
        }
        // 查询出所有权限组
        List<PermissionGroupDto> permissionGroupDtoList = permissionGroupMapper.getPermissionGroupList(permissionGroupSearchJo);
        // 将权限设置到权限组中
        for (PermissionGroupDto permissionGroupDto : permissionGroupDtoList) {
            // 先通过权限组id获取所有权限id
            QueryWrapper<PermissionGroupPermissionRelation> queryWrapper = new QueryWrapper<>();
            queryWrapper.select("permission_id").eq("permission_group_id", permissionGroupDto.getId());
            List<Object> permissionIdList = permissionGroupPermissionRelationMapper.selectObjs(queryWrapper);
            // TODO:这里通过stream，将list类型转换
            List<Integer> idList = permissionIdList.stream().map(pre -> (Integer) pre).collect(Collectors.toList());
            // 通过权限id获取权限
            List<Permission> permissionList = permissionMapper.selectBatchIds(idList);
            permissionGroupDto.setPermissionList(permissionList);
        }
        logger.info("权限组列表：{}", permissionGroupDtoList);
        return new PageInfo<>(permissionGroupDtoList);
    }

    /**
     * 添加权限组
     */
    @Transactional(rollbackFor = Exception.class)
    public void addPermissionGroup(PermissionGroupDto permissionGroupDto) {
        // TODO:1、这里需要校验权限组是否存在，以及权限的id，2、判断权限是否存在
        // 添加权限组
        permissionGroupMapper.insert(permissionGroupDto);
        // 添加权限组-权限-关系
        addPermissionGroupPermissionRelation(permissionGroupDto.getId(),permissionGroupDto.getPermissionIdList());
    }

    /**
     * 修改权限组
     */
    @Transactional(rollbackFor = Exception.class)
    public void updatePermissionGroup(PermissionGroupDto permissionGroupDto) {
        // TODO:1、这里需要校验权限组是否存在，以及权限的id，2、判断权限是否存在、3.权限名称标识唯一
        // 修改权限组
        permissionGroupMapper.updateById(permissionGroupDto);
        // 删除权限组-权限-关系
        Map<String, Object> map = new HashMap<>();
        map.put("permission_group_id", permissionGroupDto.getId());
        permissionGroupPermissionRelationMapper.deleteByMap(map);
        // 添加权限组-权限-关系
        addPermissionGroupPermissionRelation(permissionGroupDto.getId(),permissionGroupDto.getPermissionIdList());
    }

    /**
     * 删除权限组
     */
    @Transactional(rollbackFor = Exception.class)
    public void deletePermissionGroup(List<Integer> id) {
        // TODO:删除的时候需要看是否有角色关联权限组，如果有，则不允许删除
        // 删除权限组
        permissionGroupMapper.deleteBatchIds(id);
        // 删除权限组-权限-关系
        QueryWrapper<PermissionGroupPermissionRelation> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("permission_group_id", id);
        permissionGroupPermissionRelationMapper.delete(queryWrapper);
    }

    /**
     * 添加权限组-权限-关系
     */
    public void addPermissionGroupPermissionRelation(int permissionGroupId, List<Integer> permissionIdList) {
        for (Integer integer : permissionIdList) {
            PermissionGroupPermissionRelation relation = new PermissionGroupPermissionRelation();
            relation.setPermissionGroupId(permissionGroupId);
            relation.setPermissionId(integer);
            permissionGroupPermissionRelationMapper.insert(relation);
        }
    }

    /**
     * 获取所有权限组
     */
    public List<PermissionGroup> getAllPermissionGroup(){
        return permissionGroupMapper.selectList(null);
    }
}
